/*
 * @Author: Zhang Kai
 * @Date: 2021-12-31 11:25:48
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-14 11:15:39
 * @FilePath: /metricsx-standard-ui/src/views/indexlib/components/favoriteDrawer/index.tsx
 */
import {
  defineComponent,
  computed,
  watch,
  ref,
  reactive,
  onMounted
} from 'vue';
import { useStore } from '@/store';
import './index.scss';
import Table from '@/components/Table/index';
import * as RouteNames from '@/router/consts';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus/lib/index';
import API from '@/services';

const FavoriteDrawer = defineComponent({
  name: 'FavoriteDrawer',
  setup(props, { slots, attrs, emit }) {
    const store = useStore();

    const visible = computed(() => store.state.indexlibrary.drawerVisible);

    const TableLoading = ref(false);

    const tableData: any = ref([]);

    const router = useRouter();

    const isReload = ref(false);

    const pageNum = ref(1);

    const pageSize = ref(10);

    const pages = ref(1);

    /* table Column */
    const tableColumn = reactive([
      {
        label: '指标名称',
        width: 210,
        default: ({ row }: any) =>
          row.reviewStatus === 5 ? (
            <a
              class="go-detail"
              href="javascript:void(0)"
              onClick={() => goDetail(row.id)}
            >
              {row.cnName}
            </a>
          ) : (
            <>{row.cnName}</>
          )
      },
      {
        label: '业务含义',
        width: 210,
        prop: 'businessMeaning'
      },
      {
        label: '主题层级',
        width: 175,
        default: ({ row }: any) =>
          [
            row.firstSubjectName || '',
            row.secondSubjectName || '',
            row.thirdSubjectName || ''
          ].join(' | ')
      },
      {
        label: '操作',
        default: ({ row }: any) => (
          <el-button
            type="text"
            onClick={() => cancelFavoriteStatus(row, tableData)}
          >
            取消收藏
          </el-button>
        )
      }
    ]);

    const handleClose = () => {
      store.commit('indexlibrary/toggleDrawerVisible', false);
    };

    const goDetail = (id: number) => {
      // 去往详情页
      router.push({
        name: RouteNames.ROUTE_INDEXDETAIL,
        query: { id }
      });
      store.commit('indexlibrary/toggleDrawerVisible', false);
    };

    const cancelFavoriteStatus = async (row: any, tableData: any) => {
      if (row) {
        const { id } = row;
        const { code } = await API.favoriteMetrics.putFavoriteMetricsById({
          id
        });
        if (code === 200) {
          isReload.value = true;
          pageNum.value = 1;
          getFavoriteMetricsList();
          ElMessage.success('取消收藏成功');
        } else {
          ElMessage.error('取消收藏失败');
        }
      }
    };

    const getFavoriteMetricsList = async () => {
      TableLoading.value = true;
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value
      };
      try {
        const { code, data }: any =
          await API.favoriteMetrics.getFavoriteMetricsList(params);
        if (code === 200) {
          if (isReload.value) {
            tableData.value = data?.list;
          } else {
            tableData.value = [...tableData.value, ...(data?.list || [])];
          }

          pages.value = data?.pages;
        }
      } catch (error) {
        console.log(error);
      } finally {
        TableLoading.value = false;
        isReload.value = false;
      }
    };

    const pageNext = () => {
      if (pageNum.value + 1 <= pages.value) {
        pageNum.value += 1;
        getFavoriteMetricsList();
      }
    };

    watch(visible, (val: any) => {
      if (val) {
        isReload.value = true;
        getFavoriteMetricsList();
      }
    });

    return () => {
      return (
        <el-drawer
          close-on-click-modal={false}
          append-to-body={true}
          custom-class="my-favorite-drawer"
          model-value={visible.value}
          title="收藏的指标"
          direction="rtl"
          before-close={handleClose}
          size="580"
        >
          <Table
            v-loading={TableLoading.value}
            data={tableData.value}
            column={tableColumn}
          />
          {pageNum.value !== pages.value && pages.value !== 0 ? (
            <div class="show-more">
              <a href="javascript:void(0)" onClick={() => pageNext()}>
                加载更多...
              </a>
            </div>
          ) : undefined}
        </el-drawer>
      );
    };
  }
});

export default FavoriteDrawer;
